<template>
	<div class="page-container">
		<div class="el-form-modify">
			<div style="max-height: 400px; overflow: auto;">
				<el-tree
					ref="elTree"
					:data="actionList"
					show-checkbox
					node-key="id"
					:default-checked-keys="checkedKeys"
					:props="defaultProps"
					@check="onCheck"
				></el-tree>
			</div>
			<div class="mt-20">
				<el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
				<el-button @click="cancel" size="small">取消</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import { menuQuery } from "@/api/menu";
import { getActionsByRole, editRoleActions } from "@/api/roles";
export default {
	name: "RolePermission",
	data() {
		return {
			actionList: [],
			checkedKeys: [],
			defaultProps: {
				children: "children",
				label: "name"
			},
			saving: false
		};
	},
	methods: {
		async requestActions(roleId) {
			try {
				const { data } = await menuQuery();
				this.actionList = data;
			} catch (error) {
				console.log(error);
			}
		},
		async requestActionsByRole(roleId) {
			try {
				const { data } = await getActionsByRole(roleId);
				this.checkedKeys = data || [];
				this.$refs.elTree.setCheckedKeys(this.checkedKeys);
			} catch (error) {
				console.log(error);
			}
		},
		async save() {
			try {
				await editRoleActions(this.roleId, this.checkedKeys);
				this.$message.success("保存成功");
				this.cancel();
			} catch (error) {}
		},
		onCheck(data, { checkedKeys }) {
			this.checkedKeys = checkedKeys;
		},
		cancel() {
			this.$router.go(-1);
		}
	},
	created() {
		let { id } = this.$route.params;
		if (id) {
			this.roleId = id;
			this.requestActions();
			this.requestActionsByRole(id);
		} else {
			this.cancel();
		}
	}
};
</script>

<style lang="scss">
</style>
